/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov.vf;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.javlov.Option;
import net.javlov.State;

public class OptionTraces {

	protected Map<Option, OptionTrace> traces;
	
	protected OptionTrace traceTemplate;
	
	protected double threshold;
	
	public OptionTraces(OptionTrace template) {
		this(template, 0.01);
	}
	
	public OptionTraces(OptionTrace template, double threshold) {
		traces = new HashMap<Option, OptionTrace>(10);
		traceTemplate = template;
		this.threshold = threshold;
	}
	
	public OptionTrace get(State s, Option o) {
		return traces.get(o);
	}
	
	public void put(State s, Option o, OptionTrace trace) {
		traces.put(o, trace);
	}
	
	/**
	 * 
	 * @param s
	 * @param o
	 * @param delta
	 * @return true if there are no more traces for this state
	 */
	public boolean updateAll(State s, Option o, double delta) {
		Iterator<OptionTrace> itr = traces.values().iterator();
		OptionTrace tr;
		while ( itr.hasNext() ) {
			tr = itr.next();
			tr.getValues().update( tr.getOption(), tr.getTrace()*delta );
			tr.update(s, o);
			if ( tr.getTrace() < threshold )
				itr.remove();
		}
		return traces.size() == 0;
	}
	
	public int size() {
		return traces.size();
	}
	
	public OptionTraces newInstance() {
		return new OptionTraces(traceTemplate, threshold);
	}
	
	public OptionTrace newTrace() {
		return traceTemplate.newInstance();
	}
}
